<template>
    <massif-layout>
        <template v-slot:left>
            <div class="massifIndex">
                <div class="tobBox">
                    <div class="back" @click="goBack">
                        <el-icon><ArrowLeft /></el-icon>
                        <span>返回</span>
                    </div>
                    <div class="inputbox" style="margin:0 10px;" v-if="farmId">
                        <group-select className="small-el-input__inner" popperClass="samll-el-select-dropdown__list" v-model="searchInfo.landGroupId" @change="reGetData" :params="{farmId}"/>
                    </div>
                    <div class="inputbox">
                        <land-select className="small-el-input__inner" popperClass="samll-el-select-dropdown__list" v-model="dropFarmLandId" :optLists="tableData" @change="landChange"/>
                    </div>
                </div>
                <div class="btnBox">
                    <router-link :to="'/full/massif/add?farmId='+farmId" class="item">
                        <el-icon><CirclePlus /></el-icon>新增
                    </router-link>
                    <div class="item" style="position: relative;z-index:10;" @click="dialogFlag=true">
                        <el-icon><Upload /></el-icon>导入土壤成分
                    </div>
                </div>
                <div class="listBox">
                    <el-table class="small-el-table" :data="tableData" border style="width: 100%" :row-class-name="setSelectLine" @row-dblclick="goDetail" @row-click="setMapData">
                        <el-table-column prop="farmLandId" label="编号" width="50" />
                        <el-table-column prop="farmLandName" label="地块名称" show-overflow-tooltip/>
                        <el-table-column prop="areaSize" label="面积(亩)" width="100"/>
                        <el-table-column prop="groupName" label="地块分组" show-overflow-tooltip />
                    </el-table>
                </div>
                <div class="bottom-page">
                    <my-pagination @goPage="toPage" :page="page" :total="total" :finish="(page*limit)>=total"/>
                </div>
            </div>
        </template>
        <tencent-map ref="mapRef"/>
        <map-mode-control v-if="mapRef" :mapObj="mapRef"/>
        <c-dialog v-model:show="dialogFlag" v-if="dialogFlag" title="导入土壤养分数据" :showBtn="false" width="400px">
            <div class="xzmbxob">
                <div style="text-align: center;padding:20px 0">
                    <a class="lk" :href="`/boss/farmland-composition/template-file?farmId=${farmId}`">下载模板</a>
                </div>
                <div class="dran">
                    <div style="position: relative;z-index:10;">
                        <el-button type="primary" class="myBtn">导 入</el-button>
                        <input class="unbtn" type="file" @change='changeFn($event)'/>
                    </div>
                </div>
            </div>
        </c-dialog>
    </massif-layout>
</template>
  
  <script setup>
  // 这里的name是为了做页面缓存，其值要跟路由里面的name值一样
  
  import { nextTick, ref, watch, onActivated,reactive,onMounted} from 'vue'
  import{useRouter,useRoute} from "vue-router"

  import {getLandList,uploadComposition,getUptM} from '@/api/plant'
  import {message} from '@/utils/element'
  import myPagination from '@/components/custom/myPagination.vue'
  import massifLayout from '../components/layout.vue'
  import tencentMap from '@/components/custom/tencentMap.vue'
  import groupSelect from '@/components/custom/groupSelect.vue'
  import landSelect from '@/components/custom/landSelect.vue'
  import mapModeControl from '@/components/custom/mapModeControl.vue'
  import cDialog from '@/components/custom/cDialog.vue'
  import { useUserStore } from '@/pinia/modules/user'

  const router = useRouter()

  const userStore = useUserStore()
  
  const page = ref(1)
  const limit = ref(20)
  const total = ref(0)
  const mapRef = ref(null)
  const farmId = ref('') // 农场id
  const dropFarmLandId = ref('') // 下拉选择地块id
  const searchInfo = ref({})
  const tableData = ref([])
  let infowindowObj = '' // 地图标注对象
  let hoverInfowindowObj = ''
  let mapAreaObj='' // 保存绘制的区域对象
  const dialogFlag = ref(false)
  const tmData = ref({})
  
  onMounted(async ()=>{
    farmId.value = router.currentRoute.value.query.id
    get_land_list() // 获取农场下的地块
    await nextTick()
  })

  const get_land_list = async ()=>{
    const res = await getLandList({
        page:page.value,
        limit:limit.value,
        farmId:farmId.value,
        ...searchInfo.value
    })
    tableData.value = res.data
    total.value = res.total

    // 设置第一个为中心点
    let center = ''
    if(tableData.value && tableData.value.length>0){
        center = {
            lat:tableData.value[0].locationLatitude,
            lng:tableData.value[0].locationLongitude
        }
    }
    center && mapRef.value.setCenter(center.lat,center.lng)
    
    if(infowindowObj){
        infowindowObj.destroy()
    }
    createMapArea() // 在地图上创建地块区域
  }
  
  // 在地图上创建地块区域
  const createMapArea = ()=>{
    if(mapAreaObj) {
        mapAreaObj.destroy() // 先清除 
    }
    let paths = []
    tableData.value.forEach(item =>{
        const locations = JSON.parse(item.location)
        let obj = {
            farmLandId:item.farmLandId,
            itemData:item,
            path:[],
            styleId:(item.farmLandId == dropFarmLandId.value)?'styel2':'styel1'
        }
        locations.forEach(ele =>{
            obj.path.push(ele.lat)
            obj.path.push(ele.lng)
        })
        paths.push(obj)
    })
    //console.log("paths:",paths)
    mapAreaObj = mapRef.value.createArea(paths)
    mapAreaObj.on("click",function(e){
        if(e.detail.area){ // 点击了区域
            goDetail(e.detail.area)
        }
    })
    mapAreaObj.on("hover",function(e){
        if(e.detail.area){ // 点击了区域
            const item = e.detail.area.itemData
            hoverInfowindowObj && hoverInfowindowObj.destroy()  // 销毁
            if(e.detail.area.farmLandId !=dropFarmLandId.value){ // 只有不是当前选择的地块才处理
                hoverInfowindowObj = mapRef.value.setMarker2(item.locationLatitude,item.locationLongitude,mapShowTemplate(item,'mapMarker'))
            }
        }else{
            hoverInfowindowObj && hoverInfowindowObj.destroy()  // 销毁
        }
    })
  }

  // 设置地图标注
  const set_map_marker = (item,center)=>{
    if(infowindowObj){
        infowindowObj.destroy()
    }
    infowindowObj = mapRef.value.setMarker2(item.locationLatitude,item.locationLongitude,mapShowTemplate(item,'mapMarker2'))
    if(center){
        mapRef.value.setCenter(center.lat,center.lng)
    }
    // infowindows[2].on("click", function (evt) {
    //     alert(1)
    // })
  }
  // 分组选择变化事件
  const reGetData = ()=>{
    get_land_list()
    dropFarmLandId.value = ''
   // mapRef.value.clearAllMarker() // 清除所有的标记
  }

  // 设置选中高亮
  const setSelectLine = ({ row, rowIndex }) =>{
    if(row.farmLandId == dropFarmLandId.value){
        return "selectedStyle"
    }else{
        return ''
    }
  }
  // 表格行单击处理事件
  const setMapData = (row)=>{
    dropFarmLandId.value = row.farmLandId
    setSelectLine({row})
    mapRef.value.setCenter(row.locationLatitude,row.locationLongitude)
    mapRef.value.setZoom(14.8)
    createMapArea()
    set_map_marker(row)
  }
  // 地块选择变化事件
  const landChange = (item)=>{
    //set_map_marker()
    createMapArea()
    set_map_marker(item)
    mapRef.value.setCenter(item.locationLatitude,item.locationLongitude)
    mapRef.value.setZoom(14.8)
  }
  
  
  const toPage = (pageNum)=>{
    page.value = pageNum
    get_land_list()
  }
  const goBack = ()=>{
    //router.push({path:'/full/massif/index',replace:true})
    router.back(-1)
  }
  const goDetail = (row)=>{
    router.push(`/full/massif/detail?id=${row.farmLandId}`)
    //router.push({path:'/full/massif/detail',query:{id:row.id},replace:true})
  }

  const changeFn = async (e)=>{
    let file = e.target.files[0];
    let fromData = new FormData()
	fromData.append('file', file)
    const res = await uploadComposition(fromData)
    if(res.code ==0 || res.success){
        message("上传成功",2)
        dialogFlag.value = false
    }else{
        message(res.message,3)
    }
  }

  const mapShowTemplate = (item,className='mapMarker') =>{
    return `<div class="${className}">
            <div class="conbox">
                <p><b>分组名称：</b>${item.groupName}</p>
                <p>${item.locationAddress}</p>
            </div>
            <div class="conbox">
                <p><b>面积：</b>${item.areaSize}</p>
                <p><b>地块权属：</b>${item.landBelong}</p>
            </div>
        </div>`
  }
  </script>
  
  <style lang="scss" scoped>
    .massifIndex{
        box-sizing: border-box;
        display: flex;
        flex-flow: column;
        height: 100%;
        padding: 10px 0;
        overflow: hidden;
        .tobBox,.btnBox{
            display: flex;
            font-size: 12px;
            box-sizing: border-box;
            align-items: center;
            height: 30px;
            padding: 0 10px;
            flex-shrink: 0;
            .inputbox{
                flex: 1;
            }
            .back{
                display: flex;
                font-size: 12px;
                cursor: pointer;
                &:hover{
                    color: #48b27a;
                }
                span{
                    flex-shrink: 0;
                }
            }
        }
        .btnBox{
            margin: 7px 0;
            justify-content: center;
            font-weight: bold;
            .item{
                display: flex;
                line-height: 30px;
                font-size: 12px;
                align-items: center;
                color: #333;
                &+.item{
                    margin-left: 10px;
                }
                &:hover{
                    cursor: pointer;
                    color: #48b27a;
                }
            }
            i{
                font-size: 18px;
                font-weight: bold;
                color: #48b27a;
                margin: 0 2px 0 0;

            }
        }
        .listBox{
            box-sizing: border-box;
            //flex: 1;
            max-height: calc(100vh - 205px);
            flex-shrink: 0;
            width: 100%;
            padding: 0 10px;
            overflow: hidden;
            overflow-y: auto;
        }
        .bottom-page{
            box-sizing: border-box;
            flex-shrink: 0;
            height: 30px;
            padding: 0 15px;
        }
    }
    .xzmbxob{
        .lk{
            color: #0846f3;
            &:hover{
                color: #48b27a;
            }
        }
        .dran{
            display: flex;
            justify-content: center;
            position: relative;
            z-index:10;
            .unbtn{
                cursor: pointer;
                position: absolute;
                z-index: 10;
                left: 0;
                top: 0;
                width: 100%;
                height: 100%;
                opacity: 0;
                border: 0;
            }
        }
    }
  </style>
  